package com.zjw.core.algorithm;

public class BinarySearch {

    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 9, 11};
        int target = 7;
        int result = binarySearch(arr, target);
        if (result != -1) {
            System.out.println("元素找到，索引为: " + result);
        } else {
            System.out.println("元素未找到");
        }
    }

    public static int binarySearch(int[] arr,int target){
        int left = 0;
        int right = arr.length - 1;
        while (left <= right){
            int middle = left + (right - left) / 2;
            if(target == arr[middle]){
                return middle;
            } else if (target < arr[middle]) {
                right = middle - 1;
            }else if (target > arr[middle]) {
                left = middle + 1;
            }
        }
        return -1;
    }
}
